/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package argentracker.activeentity;

import java.util.Date;

import argentracker.activeentity.property.BooleanProperty;
import argentracker.activeentity.property.ByteProperty;
import argentracker.activeentity.property.DateProperty;
import argentracker.activeentity.property.IntegerProperty;
import argentracker.activeentity.property.LongProperty;
import argentracker.activeentity.property.ReferenceProperty;
import argentracker.activeentity.property.StringProperty;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;

/**
 * Active Entitis base definition, acts as a marker and implements basic behaviour.
 * 
 * Abstraction to define how to map and use an "Active Entity". Initially only defines basic events and behaviour to
 * CRUD operations on simple domain objects.
 * 
 * @author matero (matero _at_ gmail _dot_ com)
 */
public abstract class ActiveEntity<A extends ActiveEntity<A>> {

    protected Entity data;

    protected ActiveEntity() {
        this.data = createEntity();
    }

    protected ActiveEntity(Entity rawEntity) {
        this.data = rawEntity;
    }

    protected Entity createEntity() {
        return new Entity(getKind());
    }

    public <T> T get(P<T, A> property) {
        return property.in(this.data);
    }

    public Key getKey() {
        return this.data.getKey();
    }

    /**
     * Creates a Key for the represented entity with a unique id.
     * 
     * @param id
     *            unique id desired for the creaed key.
     * @return a key that holds the specified id, for the representend kind of entity.
     * @see #getKind()
     * @see KeyFactory#createKey(String, long)
     * @throws IllegalArgumentException
     *             if id is 0.
     */
    protected Key createKey(long id) throws IllegalArgumentException {
        return KeyFactory.createKey(getKind(), id);
    }

    /**
     * Creates a Key for the represented entity with a unique name.
     * 
     * @param name
     *            name desired for the creaed key.
     * @return a key that holds the specified name, for the representend kind of entity.
     * @see #getKind()
     * @see KeyFactory#createKey(String, String)
     * @throws IllegalArgumentException
     *             if id is 0.
     */
    protected Key createKey(String name) throws IllegalArgumentException {
        return KeyFactory.createKey(getKind(), name);
    }

    /**
     * @return the modeled entity kind
     */
    public String getKind() {
        return getClass().getSimpleName();
    }

    /**
     * The id used at datastore for its kind of entity.
     * 
     * @return 0 if the ActiveEntity is not persisted. A value greater than 0 in other way.
     */
    public long getId() {
        return getKey().getId();
    }

    /**
     * Saves or updates the instance.
     * 
     * @return the receiver (<code>this</code>) after the operation is doneand its state is updated in consecuence.
     */
    @SuppressWarnings("unchecked")
    public A save() {
        beforeSave();
        doSave();
        afterSave();

        return (A) this;
    }

    /**
     * Operations to be done before saving the ActiveEntity.
     */
    protected void beforeSave() {
        // nothing to be done
    }

    protected void doSave() {
        datastore().put(this.data);
    }

    /**
     * Operations to be done after saving the ActiveEntity.
     */
    protected void afterSave() {
        // nothing to be done
    }

    /**
     * Saves or updates the instance on the defined transaction.
     * 
     * @param onTransaction
     *            The transaction to use.
     * @return the receiver (<code>this</code>) after the operation is doneand its state is updated in consecuence.
     */
    @SuppressWarnings("unchecked")
    public A save(Transaction onTransaction) {
        beforeSave(onTransaction);
        doSave(onTransaction);
        afterSave(onTransaction);

        return (A) this;
    }

    /**
     * Operations to be done before saving the ActiveEntity.
     * 
     * @param onTransaction
     *            The transaction to use.
     */
    protected void beforeSave(Transaction onTransaction) {
        // nothing to be done
    }

    protected void doSave(Transaction onTransaction) {
        datastore().put(onTransaction, this.data);
    }

    /**
     * Operations to be done after saving the ActiveEntity.
     * 
     * @param onTransaction
     *            The transaction to use.
     */
    protected void afterSave(Transaction onTransaction) {
        // nothing to be done
    }

    /**
     * Deletes the instance representation on datastore.
     * 
     * @return the receiver (<code>this</code>) after the operation is doneand its state is updated, and without any
     *         key.
     */
    @SuppressWarnings("unchecked")
    public A delete() {
        beforeDelete();
        doDelete();
        afterDelete();
        return (A) this;
    }

    /**
     * Operations to be done before deleting the ActiveEntity.
     */
    protected void beforeDelete() {
        // nothing to be done
    }

    protected void doDelete() {
        datastore().delete(getKey());
    }

    /**
     * Operations to be done after deleting the ActiveEntity.
     */
    protected void afterDelete() {
        // nothing to be done
    }

    /**
     * Saves or updates the instance on the defined transaction.
     * 
     * @param onTransaction
     *            The transaction to use.
     * @return the receiver (<code>this</code>) after the operation is doneand its state is updated in consecuence.
     */
    @SuppressWarnings("unchecked")
    public A delete(Transaction onTransaction) {
        beforeDelete(onTransaction);
        doDelete(onTransaction);
        afterDelete(onTransaction);
        return (A) this;
    }

    /**
     * Operations to be done before deleting the ActiveEntity over some transaction.
     * 
     * @param entity
     *            entity to be putted on the datastor representing the instance.
     */
    protected void beforeDelete(Transaction onTransaction) {
        // nothing to be done
    }

    protected void doDelete(Transaction onTransaction) {
        datastore().delete(onTransaction, getKey());
    }

    /**
     * Operations to be done after deleting the ActiveEntity the ActiveEntity over some transaction.
     * 
     * @param entity
     *            entity that has been putted on the datastore representing the instance.
     */
    protected void afterDelete(Transaction onTransaction) {
        // nothing to be done
    }

    @SuppressWarnings("unchecked")
    public A load(Entity entity) {
        if (entity == null) {
            throw new IllegalArgumentException("entity can not be null");
        }
        this.data = entity;
        return (A) this;
    }

    /**
     * Gets the datastore where entities are allocated.
     * 
     * @return a not <code>null</code> {@link DatastoreService}.
     */
    protected DatastoreService datastore() {
        return DatastoreServiceFactory.getDatastoreService();
    }

    /*
     * property factory methods
     */

    protected static final <A extends ActiveEntity<A>> P<Boolean, A> booleanProp() {
        return new BooleanProperty<A>();
    }

    protected static final <A extends ActiveEntity<A>> P<Boolean, A> booleanProp(String name) {
        return new BooleanProperty<A>(name);
    }

    protected static final <A extends ActiveEntity<A>> P<String, A> stringProp() {
        return new StringProperty<A>();
    }

    protected static final <A extends ActiveEntity<A>> P<String, A> stringProp(String name) {
        return new StringProperty<A>(name);
    }

    protected static final <A extends ActiveEntity<A>> P<Byte, A> byteProp() {
        return new ByteProperty<A>();
    }

    protected static final <A extends ActiveEntity<A>> P<Byte, A> byteProp(String name) {
        return new ByteProperty<A>(name);
    }

    protected static final <A extends ActiveEntity<A>> P<Integer, A> integerProp() {
        return new IntegerProperty<A>();
    }

    protected static final <A extends ActiveEntity<A>> P<Integer, A> integerProp(String name) {
        return new IntegerProperty<A>(name);
    }

    protected static <AE extends ActiveEntity<AE>> P<Long, AE> longProp() {
        return new LongProperty<AE>();
    }

    protected static <AE extends ActiveEntity<AE>> P<Long, AE> longProp(String name) {
        return new LongProperty<AE>(name);
    }

    protected static final <A extends ActiveEntity<A>> P<Date, A> dateProp() {
        return new DateProperty<A>();
    }

    protected static final <A extends ActiveEntity<A>> P<Date, A> dateProp(String name) {
        return new DateProperty<A>(name);
    }

    protected static final <R extends ActiveEntity<R>, A extends ActiveEntity<A>> P<R, A> hasOne(
            Class<R> referencedClass) {
        return new ReferenceProperty<R, A>(referencedClass);
    }

    protected static final <R extends ActiveEntity<R>, A extends ActiveEntity<A>> P<R, A> hasOne(
            Class<R> referencedClass, String name) {
        return new ReferenceProperty<R, A>(referencedClass, name);
    }
}
